package com.zhangzhan.gulimallproduct.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhangzhan.gulimallcommcon.enums.product.AttrType;
import com.zhangzhan.gulimallcommcon.util.CopyBean;
import com.zhangzhan.gulimallcommcon.util.PageUtils;
import com.zhangzhan.gulimallcommcon.util.Query;
import com.zhangzhan.gulimallproduct.dao.AttrDao;
import com.zhangzhan.gulimallproduct.dao.AttrGroupDao;
import com.zhangzhan.gulimallproduct.dao.CategoryDao;
import com.zhangzhan.gulimallproduct.entity.*;
import com.zhangzhan.gulimallproduct.service.AttrAttrgroupRelationService;
import com.zhangzhan.gulimallproduct.service.AttrService;
import com.zhangzhan.gulimallproduct.service.CategoryService;
import com.zhangzhan.gulimallproduct.service.ProductAttrValueService;
import com.zhangzhan.gulimallproduct.vos.AttrRespVo;
import com.zhangzhan.gulimallproduct.vos.AttrVo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Resource
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Resource
    private CategoryDao categoryDao;

    @Resource
    private CategoryService categoryService;

    @Resource
    private AttrGroupDao attrGroupDao;

    @Resource
    private ProductAttrValueService productAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * 新增属性时同时 添加属性和属性组中间表数据
     *
     * @param attrVo
     */
    @Transactional
    @Override
    public void saveDetailed(AttrVo attrVo) {
        AttrEntity attrEntity = CopyBean.copyBean(attrVo, AttrEntity.class);

        this.save(attrEntity);
        //添加关联关系（属性和属性分组），保存到中间库

        if (Objects.equals(attrVo.getAttrType(), AttrType.BASE_TYPE.getCode())) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrSort(0);
            attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
        }


    }

    /**
     * 查询时判断分类id和搜索栏key信息 同时设置分类和属性分组的名字
     *
     * @param params
     * @param catelogId
     * @param attrType
     * @return
     */
    @Override
    public PageUtils attrTypeList(Map<String, Object> params, Long catelogId, String attrType) {
        PageUtils pageUtils = null;
        LambdaQueryWrapper<AttrEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AttrEntity::getAttrType, "sale".equals(attrType) ? AttrType.SALE_TYPE.getCode() : AttrType.BASE_TYPE.getCode());

        String key = (String) params.get("key");
        if (StrUtil.isNotBlank(key)) {
            //根据分类id查询基本信息
            IPage<AttrEntity> page = this.page(
                    new Query<AttrEntity>().getPage(params),
                    wrapper
                            .eq(AttrEntity::getCatelogId, key).or()
                            .eq(AttrEntity::getAttrId, key).or()
                            .like(AttrEntity::getAttrName, key)
            );
            pageUtils = new PageUtils(page);
        }

        //catelogId=0查询全部
        if (!Objects.isNull(catelogId) && Objects.isNull(pageUtils)) {
            pageUtils = new PageUtils(this.page(
                    new Query<AttrEntity>().getPage(params),
                    wrapper
                            .eq(catelogId != 0, AttrEntity::getCatelogId, catelogId)

            ));
        }

        //设置分类和属性分组的名字
        if (!Objects.isNull(pageUtils)) {
            List<?> list = pageUtils.getList();
            List<AttrRespVo> attrRespVos = CopyBean.copyBeanList(list, AttrRespVo.class);
            attrRespVos.forEach((vo) -> {
                CategoryEntity category = categoryDao.selectOne(Wrappers.<CategoryEntity>lambdaQuery()
                        .eq(CategoryEntity::getCatId, vo.getCatelogId()));
                vo.setCatelogName(category.getName());

                if (Objects.equals(vo.getAttrType(), AttrType.BASE_TYPE.getCode())) {
                    AttrAttrgroupRelationEntity relation = attrAttrgroupRelationService.getOne(Wrappers.<AttrAttrgroupRelationEntity>lambdaQuery()
                            .eq(AttrAttrgroupRelationEntity::getAttrId, vo.getAttrId()));

                    if (!Objects.isNull(relation)) {
                        AttrGroupEntity attrGroup = attrGroupDao.selectOne(Wrappers.<AttrGroupEntity>lambdaQuery()
                                .eq(AttrGroupEntity::getAttrGroupId, relation.getAttrGroupId()));
                        if (!Objects.isNull(attrGroup)) {
                            vo.setGroupName(attrGroup.getAttrGroupName());
                        }
                    }
                }
            });

            pageUtils.setList(attrRespVos);
        }


        return pageUtils;

    }

    /**
     * 属性修改回显  回显基本信息和分类、属性组路径
     *
     * @param attrId
     * @return
     */
    @Override
    public AttrRespVo getByIdCorrelationPath(Long attrId) {
        AttrEntity attr = this.getById(attrId);
        AttrRespVo attrRespVo = null;
        if (!Objects.isNull(attr)) {
            attrRespVo = CopyBean.copyBean(attr, AttrRespVo.class);

            CategoryEntity category = categoryDao.selectOne(Wrappers.<CategoryEntity>lambdaQuery()
                    .eq(CategoryEntity::getCatId, attrRespVo.getCatelogId()));

            Long[] catelogIdPath = categoryService.getCatelogIdPath(category.getCatId());

            attrRespVo.setCatelogPath(catelogIdPath);

            if (Objects.equals(attr.getAttrType(), AttrType.BASE_TYPE.getCode())) {
                AttrAttrgroupRelationEntity relation = attrAttrgroupRelationService.getOne(Wrappers.<AttrAttrgroupRelationEntity>lambdaQuery()
                        .eq(AttrAttrgroupRelationEntity::getAttrId, attrRespVo.getAttrId()));
                if (!Objects.isNull(relation)) {
                    attrRespVo.setAttrGroupId(relation.getAttrGroupId());
                }
            }
        } else {
            throw new RuntimeException("未知异常");
        }

        return attrRespVo;
    }


    @Transactional
    @Override
    public void updateOrSaveDetailed(AttrVo attrVo) {
        //修改属性信息后 同时修改属性分组中间表信息
        AttrEntity attrEntity = CopyBean.copyBean(attrVo, AttrEntity.class);
        this.updateById(attrEntity);

        if (Objects.equals(attrVo.getAttrType(), AttrType.BASE_TYPE.getCode())) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());

            long count = attrAttrgroupRelationService.count(Wrappers.<AttrAttrgroupRelationEntity>lambdaQuery()
                    .eq(AttrAttrgroupRelationEntity::getAttrId, attrVo.getAttrId()));
            //判断如果中间表数据为0 就是新增
            if (count == 0) {
                attrAttrgroupRelationEntity.setAttrId(attrVo.getAttrId());
                attrAttrgroupRelationEntity.setAttrSort(0);
                attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
            } else {
                attrAttrgroupRelationService.update(attrAttrgroupRelationEntity, Wrappers.<AttrAttrgroupRelationEntity>lambdaUpdate()
                        .eq(AttrAttrgroupRelationEntity::getAttrId, attrVo.getAttrId()));
            }
        }


    }

    @Override
    public void attrDeletes(List<Long> attrIds) {
        this.getBaseMapper().attrDeletes(attrIds);
    }

    @Override
    public List<ProductAttrValueEntity> baseListforspu(Long spuId) {
        return productAttrValueService.list(Wrappers.<ProductAttrValueEntity>lambdaQuery().eq(ProductAttrValueEntity::getSpuId, spuId));
    }

    @Override
    public void attrValueUpdate(Long spuId, List<ProductAttrValueEntity> productAttrValueEntities) {

        for (ProductAttrValueEntity productAttrValueEntity : productAttrValueEntities) {
            productAttrValueService.update(productAttrValueEntity, Wrappers.<ProductAttrValueEntity>lambdaUpdate()
                    .eq(ProductAttrValueEntity::getAttrId, productAttrValueEntity.getAttrId())
                    .eq(ProductAttrValueEntity::getSpuId, spuId));

            AttrEntity attr = this.getById(productAttrValueEntity.getAttrId());
            if (StrUtil.isNotBlank(attr.getValueSelect())){
                if (!attr.getValueSelect().contains(productAttrValueEntity.getAttrValue())) {
                    attr.setValueSelect(attr.getValueSelect() + ";" + productAttrValueEntity.getAttrValue());
                    attr.setValueType(1);
                }
                this.update(attr,Wrappers.<AttrEntity>lambdaUpdate()
                        .eq(AttrEntity::getAttrId,attr.getAttrId()));
            }else {
                attr.setValueSelect(productAttrValueEntity.getAttrValue());
                this.update(attr,Wrappers.<AttrEntity>lambdaUpdate()
                        .eq(AttrEntity::getAttrId,attr.getAttrId()));
            }

        }

    }
}